import {
	v4
} from 'uuid';
import {
	MQTT_IP,
	MQTT_OPTIONS
} from '@/common/mqtt.js';
var mqtt = require('mqtt/dist/mqtt.js')

const mqttSocket = {
	state:{
		client:null,
		topic:'alarm'
	},
	mutations:{
		MQTT_INIT(state) {
			console.log('链接了')
			MQTT_OPTIONS.clientId = v4()
			// #ifdef H5
			state.client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
			// #endif
			// #ifdef MP-WEIXIN||APP-PLUS
			state.client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS)
			// #endif
			state.client.on('connect', function() {
				console.log('连接成功')
				state.client.subscribe(state.topic, function(err) {
					if (!err) {
						console.log('订阅成功')
					}
				})
			}).on('reconnect', function(error) {
				console.log('正在重连...', state.topic)
			}).on('error', function(error) {
				console.log('连接失败...', error)
			}).on('end', function() {
				console.log('连接断开')
			}).on('message', function(topic, message) {
				// let encodedString = String.fromCharCode.apply(null, new Uint8Array(message));
				console.log('接收推送信息：', message.toString())
			})
		},
		MQTT_END(state){
			state.client.end(true)
		}
	}
}

export default mqttSocket;

